package com.zaofan.controller;

import com.zaofan.utils.JsonUtils;
import com.zaofan.utils.WebUtils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/upload")
public class UploadController extends BaseServlet {
	private static final long serialVersionUID = 1L;

	protected void image(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String images = "";
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		String random = new Random().nextInt() + "";
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (!item.isFormField()) {
					InputStream in = item.getInputStream();
					String path = WebUtils.makeDir(this.getServletContext()
							.getRealPath("/product_image"), random + "")
							+ "/"
							+ WebUtils.getUUID()
							+ "_"
							+ random
							+ item.getName().substring(
									item.getName().lastIndexOf("."));
					FileOutputStream out = new FileOutputStream(this
							.getServletContext().getRealPath("/product_image")
							+ "/" + path);
					BufferedOutputStream bos = new BufferedOutputStream(out);
					int len = 0;
					byte[] buff = new byte[1024];
					while ((len = in.read(buff)) != -1) {
						bos.write(buff, 0, len);
					}
					bos.close();
					images = "/product_image/" + path + ",";
				} else {

				}
			}
			if (images != null) {
				images = images.substring(0, images.length() - 1);
				JsonUtils.writeSuccessJson("操作成功!!", images, response);
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		JsonUtils.writeSuccessJson("上次失败!!", "", response);
	}



	protected void bigImage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.print("进来了上传");
		Calendar calendar = Calendar.getInstance();
		String images = ""+calendar.getTimeInMillis()+new Random().nextInt()+".jpg";
		String imagesName = images;
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("utf-8");
		String random = new Random().nextInt() + "";
		try {
			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (!item.isFormField()) {
					InputStream in = item.getInputStream();
					String path =  "/usr/share/nginx/zz/bigImage/";
					FileOutputStream out = new FileOutputStream(path+images);
					BufferedOutputStream bos = new BufferedOutputStream(out);
					int len = 0;
					byte[] buff = new byte[1024];
					while ((len = in.read(buff)) != -1) {
						bos.write(buff, 0, len);
					}
					bos.close();
					images =  path + images;
				} else {

				}
			}

			if (images != null) {
				String fileName  = createHtml(imagesName);
				if (!fileName.equals("")){
					JsonUtils.writeSuccessJson("操作成功!!", fileName, response);
				}else{
					JsonUtils.writeSuccessJson("上次失败!!", "", response);
				}


			}
		} catch (Exception e) {
			e.printStackTrace();
			JsonUtils.writeSuccessJson("上次失败!!", "", response);
		}
		JsonUtils.writeSuccessJson("上次失败!!", "", response);
	}

	private String createHtml(String imagesName) {
		String content = new String();

		content= "<!DOCTYPE html>"+
					 "<html>"+
        				 "<head>"+
                 			"<meta charset='UTF-8'>" +
                 			"<meta name='viewport' content='width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no'/>"+
                 			"<title></title>"+
 				 			"<style>"+
				 				"*{"+
				 					"padding: 0;"+
				 					"margin: 0;"+
								"}"+
				 				"html,body{"+
				 					"width: 100%;"+
				 					"height: 100%;"+
				 				"}"+
				 				"img{"+
				 					"width: 100%;"+
			 	 				"}"+
 				 			"</style>"+
        		 		"</head>"+
        	 			 "<body>"+
 				 			"<img src=http://static.52letsgo.cn/zz/bigImage/"+imagesName+">"+
        		 		"</body>"+
				 "</html>";
		String path =  "/usr/share/nginx/fe/user/apphtml/bigImage/";
		Calendar calendar = Calendar.getInstance();
		String fileName = ""+calendar.getTimeInMillis()+new Random().nextInt()+".html";
		try{
			File f = new File(path+fileName);
			BufferedWriter output = new BufferedWriter(new FileWriter(f));
			output.write(content);
			output.close();
			return 	"www.52letsgo.cn/fe/user/apphtml/bigImage/"+fileName;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return "";
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
	}

}
